package com.biqee.service.juhuasuan.impl;

import java.io.File;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.biqee.exception.AccessBlockException;
import com.biqee.model.JuHuaSuanItemOfPage;
import com.biqee.model.JuHuaSuanItemOfPage.JuHuaSuanItemStatus;
import com.biqee.service.juhuasuan.ItemParser;
import com.biqee.util.JsoupUtil;
import com.biqee.util.TaobaoAccessUtil;

public class ItemParserImpl implements ItemParser {
	private static final Logger logger = Logger.getLogger(ItemParserImpl.class);
	
	@Override
	public void fillItemInfo(String htmlString, JuHuaSuanItemOfPage item) {
		Document doc = createDocument(htmlString);
		if(doc == null) {
			logger.error("create doc failed. htmlString: " + htmlString);
			return;
		}
		
		if(TaobaoAccessUtil.isBlocked(doc)) {
			throw new AccessBlockException("taobao block us!");
		}

		if(isRest(doc)) {
			logger.error("rest exception! itemId: " + item.getItemId());
			return;
		}
		
		if(!isJuMainFound(doc)) {
			logger.error("juMainDiv not found! div.ju-main is missing. htmlString: " + htmlString);
			return;
		}
		
		fillItemInfo(doc, item);
	}

	@Override
	public JuHuaSuanItemStatus getJuHuaSuanItemStatus(String htmlString,
			String itemId) {
		Document doc = createDocument(htmlString);
		if(doc == null) {
			logger.error("create doc failed. for itemId: " + itemId + ", htmlString: " + htmlString);
			return JuHuaSuanItemStatus.UNKNOWN;
		}
		
		if(TaobaoAccessUtil.isBlocked(doc)) {
			throw new AccessBlockException("taobao block us!");
		}
		
		if(isRest(doc)) {
			logger.error("rest exception. itemId: " + itemId);
			return JuHuaSuanItemStatus.TIME_OUT;
		}
		
		if(!isJuMainFound(doc)) {
			logger.error("juMainDiv not found! div.ju-main is missing. htmlString: " + htmlString);
			return JuHuaSuanItemStatus.UNKNOWN;
		}
		
		return getJuHuaSuanItemStatus(doc, itemId);
	}

	private boolean isRest(Document doc) {
		Element homepageDiv = doc.select("div.homepage").first();
		if(homepageDiv != null) {
			Elements subDivs = homepageDiv.select("div");
			for(Element subDiv : subDivs) {
				String classStr = subDiv.attr("class");
				if("except rest".equalsIgnoreCase(classStr)) {
					return true;
				}
			}
		}
		
		return false;
	}
	
	private boolean isJuMainFound(Document doc) {
		Element juMainDiv = doc.select("div.ju-main").first();
		return (juMainDiv != null);
	}
	
	private Document createDocument(String htmlString) {
		Document doc = JsoupUtil.createDocument(htmlString);
		if(doc == null) {
			logger.error("create doc failed. for String htmlString: " + htmlString);
			return null;
		}
		
		return doc;
	}
	
	private static final String STATUS_PREFIX = "main-box ";
	private JuHuaSuanItemStatus getJuHuaSuanItemStatus(Document doc, String itemId) {
		Element juMainDiv = doc.select("div.ju-main").first();
		Elements divElements = juMainDiv.select("div");
		for(Element element : divElements) {
			String divClassStr = element.attr("class");
			if(divClassStr.startsWith(STATUS_PREFIX)) {
				divClassStr = divClassStr.substring(STATUS_PREFIX.length());
				
				if(divClassStr.contains(JuHuaSuanItemStatus.SOLD_OUT.getStatus())) {
					return JuHuaSuanItemStatus.SOLD_OUT;
				}
				
				if(divClassStr.contains(JuHuaSuanItemStatus.AVAILABLE.getStatus())) {
					return JuHuaSuanItemStatus.AVAILABLE;
				}
				if(divClassStr.contains(JuHuaSuanItemStatus.CHANCE.getStatus())) {
					return JuHuaSuanItemStatus.AVAILABLE;
				}
				
				if(divClassStr.contains(JuHuaSuanItemStatus.TIME_OUT.getStatus())) {
					return JuHuaSuanItemStatus.TIME_OUT;
				}

				if(divClassStr.contains(JuHuaSuanItemStatus.NOT_BEGIN.getStatus())) {
					return JuHuaSuanItemStatus.NOT_BEGIN;
				}
				
				logger.error("unknown status, item: " + itemId + ", status: " + divClassStr);
				return JuHuaSuanItemStatus.UNKNOWN;
			}
		}
		
		logger.error("token: " + STATUS_PREFIX + " not found. return unknown status. itemId: " + itemId);
		return JuHuaSuanItemStatus.UNKNOWN;
	}
	
	private boolean isJieTiPrice(Element juMainDiv) {
		Elements divElements = juMainDiv.select("div");
		for(Element element : divElements) {
			String divClass = element.attr("class");
			if(divClass.contains("jieti")) {
				return true;
			}
		}
		
		return false;
	}
	
	private String parseDingJinPrice(Element juMainDiv) {
		Elements divElements = juMainDiv.select("div");
		for(Element element : divElements) {
			String divClass = element.attr("class");
			if(divClass.contains("item-buy")) {
				Element dingJinElement = element.select("strong.J_juPrices").first();
				String dingJinStr = dingJinElement.text();
				// 跳过开头的字符： ¥		
				return dingJinStr.substring(1);
			}
		}
		
		return "";
	}
	
	private void fillItemInfo(Document doc, JuHuaSuanItemOfPage item) {
		JuHuaSuanItemStatus status = getJuHuaSuanItemStatus(doc, item.getItemId());
		item.setStatus(status);
		
		Element descDiv = doc.select("div.item_share").first();
		if(descDiv == null) {
			logger.error("no item_share found for item: " + item.getItemId());
			return;
		}
		
		String dataItemId = descDiv.attr("data-itemid");
		if(!item.getItemId().equals(dataItemId)) {
			logger.error("itemId not match, expected: " + item.getItemId() + ", actual: " + dataItemId);
			return;
		}
		
		String dataPrice = descDiv.attr("data-itemprice");
		String dataItemName = descDiv.attr("data-itemname");		
		String dataItemPic = descDiv.attr("data-itempic");
		item.setDescription(dataItemName);
		item.setImgUrl(dataItemPic);
		item.setJuPrice(dataPrice);

        Element priceDl = doc.select("dl.item-prices").first();
        Element priceDd = priceDl.select("dd.price").first();
        String price = priceDd.text();
        // 跳过开头的字符： ¥
        item.setOldPrice(price.substring(1));
        Element juMainDiv = doc.select("div.ju-main").first();
        if(isJieTiPrice(juMainDiv)) {
        	Element juPriceDd = priceDl.select("dd.minprice").first();
        	String juPrice = juPriceDd.text();
            // 跳过开头的字符： ¥
            item.setJuPrice(juPrice.substring(1));
            
            String dingjinPrice = parseDingJinPrice(juMainDiv);
            item.setDingjin(dingjinPrice);
	    } 
        
        Element picboxDiv = doc.select("div.picbox").first();
        Element picDiv = picboxDiv.select("div.pic").first();
        Element detailUrlElement = picDiv.select("a").first();
		String detailUrl = detailUrlElement.attr("href");
		if(detailUrl.contains(item.getItemId())) {
			item.setDetailUrl(detailUrl);	
		} else {
			logger.error("bad detailUrl: " + detailUrl + ", wantItemId: " + item.getItemId());
		}
	}

	
	
	public static void main(String[] args) throws Exception {
		String filePath = "D:\\work\\biqee\\test-pages\\taobao\\juhuasuan\\rest.html";
		File file = new File(filePath);
		Document doc = Jsoup.parse(file, "gbk");

		ItemParserImpl parser = new ItemParserImpl();
		JuHuaSuanItemOfPage item = new JuHuaSuanItemOfPage();
		item.setItemId("10183904656");
		parser.fillItemInfo(doc.html(), item);
		
		String desc = ToStringBuilder.reflectionToString(item, ToStringStyle.MULTI_LINE_STYLE);
		System.out.println(desc);
	}
}
